package com.gxgeek.fastdfsweb;

import com.alibaba.fastjson.JSONObject;
import com.gxgeek.fastdfsweb.dto.FastDFSFile;
import com.gxgeek.fastdfsweb.service.FastdfsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;

@SpringBootApplication
@RequestMapping("/file")
@RestController
public class FastdfsWebApplication {


	@Autowired
	FastdfsUtil fdfsClient;
	public static void main(String[] args) {
		SpringApplication.run(FastdfsWebApplication.class, args);
	}



	@PostMapping(value = "/upload")
	public String uploadFile(@RequestParam("testFile") MultipartFile  uploadFile, HttpServletRequest request,
							 HttpServletResponse response) {
		String originalFilename = uploadFile.getOriginalFilename();
		String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
		JSONObject jsonObj = new JSONObject();
		try {
			FastDFSFile fdfsFile = new FastDFSFile();
			fdfsFile.setContent(uploadFile.getBytes());
			fdfsFile.setSuffix(fileSuffix);
			String[] uploadResult = fdfsClient.upload(fdfsFile);
			jsonObj.put("success", "Y");
			jsonObj.put("groupName", uploadResult[0]);
			jsonObj.put("remoteFileName", uploadResult[1]);
			return jsonObj.toJSONString();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return jsonObj.toJSONString();
	}


	@RequestMapping(value = "/download", method = RequestMethod.GET)
	public ResponseEntity<byte[]> downloadFile(@RequestParam(value = "groupName") String groupName,
											   @RequestParam(value = "remoteFileName")String remoteFileName, HttpServletResponse response)
			throws Exception {

		String fileName = remoteFileName.substring(remoteFileName.lastIndexOf("/") + 1);
		response.setCharacterEncoding("utf-8");
		response.setContentType("multipart/form-data");
		response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
		try {

			OutputStream os = response.getOutputStream();
			byte[] b = fdfsClient.downloadFile(groupName, remoteFileName);
			os.write(b, 0, b.length);
			os.close();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}



}
